home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!fersys.demon.co.uk
- From: mlb@fersys.demon.co.uk
- Newsgroups: comp.lang.c
- Subject: Global variables in a multiple-sourcefile application
- Date: Tue, 19 Mar 1996 17:19:08 GMT
- Message-ID: <827255412.29892.0@fersys.demon.co.uk>
- X-NNTP-Posting-Host: fersys.demon.co.uk
- X-Broken-Date: Tue, 19 Mar 96 11:39 GMT
- Content-Type: text
- Content-Length: 1896
- X-Mail2News-Path: relay-4.mail.demon.net!post.demon.co.uk!relay-4.mail.demon.net!post.demon.co.uk!fersys.demon.co.uk
-
- I have two questions about the use of global variables in a
- multiple-sourcefile application:
-
- 1) If I have a global variable x that is used in both source files of
- an application, but I don't need it initialised in its definition,
- I would generally put "int x;" in one and "extern int x;" in the other.
-
- However, is there anything unsafe about putting a declaration in a header
- file included by both files, without a definition in either file, or
- do I really need a definition in one of the files?
-
- i.e. is this OK?:
-
- common.h
- ========
- int x;
-
-
- a.c b.c
- === ===
- #include "common.h" #include "common.h"
-
- main () some_func()
- { {
- x = 3; int y;
-
- ... y = x;
- } ...
- }
-
- 2) Following on from q1, what happens if two source-files each contain
- a global variable declaration for the same variable name, but each has
- a different type (by accident or possibly deliberately)?
- The programs appear to compile, and behave as though
- the variable is cast appropriately.
- The example below should clarify what I mean (prototypes etc omitted):
-
- a.c b.c
- === ===
-
- int x; short x;
-
- main() f()
- { {
- x = 3; printf ("x=%d\n", x);
- f(); x = 1;
- printf("x=%d\n", x); }
- }
-
- The exact behaviour appears to depend on the endian-ness of the machine,
- size of short and int etc, e.g. on my machine I get the following output:
- x=0
- x=65539
-
- but the same variable appears to be accessed, but
- a.c treats it as an int, and b.c as a short. This appears dangerous.
-
- Does anyone have any light to shed on the above issues. (I have an old
- posting of C.Torek's that discussed "tentative" declarations briefly,
- but it didn't address the subject fully).
-
- TIA
-
- Mark Bergman Email: mlb@fersys.co.uk
- Ferranti Syseca Ltd. Tel: 0161-946 7178
- Wythenshawe, Manchester, UK Fax: 0161-946 7001
-